package com.bluesky.drcp.persistence.dao.hibernate;

import java.util.List;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.bluesky.drcp.business.Function;
import com.bluesky.drcp.persistence.dao.FunctionDao;

public class FunctionDaoImpl extends HibernateDaoSupport implements FunctionDao {
	static String ParentIdOfRoot = "{root}";

	public List getChildren(String id) {
		return getHibernateTemplate()
				.find("from Function where parentId=?", id);

	}

	public Function getRoot() {
		List list = getHibernateTemplate().find(
				"from Function where parentId is null or parentId=?",
				ParentIdOfRoot);
		if (list.isEmpty())
			throw new RuntimeException(
					"can not found root function, its parentId should be null.");

		if (list.size() > 1)
			throw new RuntimeException("found more than one root functions");

		Function function = (Function) list.get(0);
		return function;
	}

	public Function get(String id) {
		return (Function) getHibernateTemplate().get(Function.class, id);
	}

	public Function getByParentIdAndName(String parentId, String name) {
		List list = getHibernateTemplate().find(
				"from Function where parent_id=? and name=?",
				new Object[] { parentId, name });
		if (list.isEmpty())
			return null;

		if (list.size() > 1)
			throw new RuntimeException("found more than one root functions");

		Function function = (Function) list.get(0);
		return function;
	}

	public List getAll() {
		return getHibernateTemplate().find("from Function");
	}

	public void delete(String id) {
		Function func = (Function) getHibernateTemplate().get(Function.class,
				id);
		getHibernateTemplate().delete(func);
	}

	public String save(Function function) {
		getHibernateTemplate().save(function);

		return function.getId();
	}

	public void update(Function function) {
		getHibernateTemplate().update(function);
	}

}
